#include <iostream>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Thread.hpp"
#include "LockGuard.hpp"
#include "InetAddr.hpp"

using namespace std;

class ThreadDate
{
public:
    ThreadDate(int sockfd, InetAddr addr)
        : _sockfd(sockfd), _addr(addr)
    {
    }

    ~ThreadDate()
    {
    }

public:
    int _sockfd;
    struct InetAddr _addr;
};

void Usage(const string &proc)
{
    cout << proc << " serverip serverport\n"<< endl;
}

void RecverRoutine(ThreadDate td)
{
    struct sockaddr_in temp;
    socklen_t tlen = sizeof(temp);
    char inbuffer[1024];
    while (1)
    {
        int m = recvfrom(td._sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&temp, &tlen);
        if (m > 0)
        {
            inbuffer[m] = 0;
            cerr << td._addr.PrintDebug() << inbuffer << endl;
        }
    }
}

void SenderRoutine(ThreadDate td)
{
    string buffer;
    while (1)
    {
        cout << "Please Enter# ";
        getline(cin, buffer);

        int n = sendto(td._sockfd, buffer.c_str(), buffer.size(), 0, (struct sockaddr *)&td._addr.GetAddr(), sizeof(td._addr));
        if (n < 0)
            break;
    }
}

// ./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    int clientfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (clientfd < 0)
    {
        cout << "create socket fail\n"
             << endl;
        exit(1);
    }
    cout << "create socket success : " << clientfd << endl;

    struct sockaddr_in ServerSocket;
    memset(&ServerSocket, 0, sizeof(ServerSocket));
    socklen_t Slen = sizeof(ServerSocket);
    ServerSocket.sin_family = AF_INET;
    ServerSocket.sin_addr.s_addr = inet_addr(argv[1]);
    ServerSocket.sin_port = htons(stoi(argv[2]));

    ThreadDate td(clientfd, ServerSocket);
    Thread<ThreadDate> sender("sender", SenderRoutine, td);
    Thread<ThreadDate> recver("recver", RecverRoutine, td);

    sender.Start();
    recver.Start();

    sender.Join();
    recver.Join();

    close(clientfd);

    return 0;
}
